// downloadManager.js
//打开下载监听
function openDownloadManagerNotifi(){
	//监听附件下载
	api.addEventListener({
	    name: 'startDownloadAttachmentNotifi'
	}, function(ret, err) {
	
	    startDownloadAttachment(ret.value);
	});
	//监听文件下载
	api.addEventListener({
	    name: 'startDownloadFileNotifi'
	}, function(ret, err) {
	    startDownloadFile(ret.value);
	});
}
//开始下载文件
function startDownloadFile(fileData){
	var fileid = fileData.fileid;//文件id
	var filename = fileData.filename;//文件名
	var fileurl = fileData.fileurl;//文件链接
	if (fileurl.indexOf("http://") < 0 || fileurl.indexOf("https://") < 0) {
		fileurl = 'http://bos.cfnet.org.cn' + fileurl;
	}
	var pathSuffix = '/freeCourseFile/' + fileid + '/' + filename;//相对路径
	var filepath = api.cacheDir + pathSuffix;//绝对路径
	api.download({
	    url: fileurl,
	    savePath: filepath,
	    report: true,
	    cache: true,
	    allowResume: true
	}, function(ret, err) {
	    api.sendEvent({
	        name: 'downloadFreeCourseFileNotifi',
	        extra: {
	            ret : ret, 
	            err : err,
	            fileid : fileid,
	            filename : filename
	        }
	    });
	    if(ret.state == 2){//下载失败
	    	api.toast({
	    	    msg: '文件：' + filename + '下载失败!'
	    	});
	    }
	});
}
//开始下载附件
function startDownloadAttachment(attData){
	var attid = attData.id;//附件id
	var attname = attData.name;//附件名
	var atturl = attData.url;//附件链接

	var pathSuffix = '/attachment/' + attname;//相对路径
	var filepath = api.cacheDir + pathSuffix;//绝对路径
	api.download({
	    url: atturl,
	    savePath: filepath,
	    report: true,
	    cache: true,
	    allowResume: true
	}, function(ret, err) {
	
	    api.sendEvent({
	        name: 'downloadAttachmentNotifi',
	        extra: {
	            ret : ret, 
	            err : err,
	            attid : attid
	        }
	    });
	    if (ret.state == 1) {//下载完成
	    	var sql = "UPDATE t_attachment SET isdownload = '1', size = '"+ret.fileSize+"',localpath = '"+pathSuffix+"' WHERE id = "+attid+";";
	    	executeSQL(sql, function(ret, err){});
	    }else if(ret.state == 2){//下载失败
	    	api.toast({
	    	    msg: '附件：' + attname + '下载失败!'
	    	});
	    }
	});
}